<?php
/**
 * Created by PhpStorm.
 * User: mr.lee
 * Date: 2018/10/22
 * Time: 6:10 PM
 */

namespace app\api\controller;


use Alipay\Alipayobj;
use app\common\controller\ActionLogs;
use app\common\controller\Bonus;
use app\common\controller\CardDedu;
use app\common\controller\Deviceobj;
use app\common\controller\FeiePrint;
use app\common\controller\Fenzhang;
use app\common\controller\MachExtend;
use app\common\controller\TemplateMsg;
use app\common\model\Agent;
use app\common\model\CardMember;
use app\common\model\Merchant;
use app\common\model\Paylog;
use app\common\model\WxOpen;
use think\Db;
use Wechat\Wxobjopen;

class OfficialPay extends Pub
{
    public function getpay($param, $pays)
    {

        $User = new Merchant();
        $Paylog = new Paylog();
        $machinfos = $User->where(array('id' => $param['merchantid']))->find();
        if (isset($param['out_trade_no']) && !empty($param['out_trade_no'])) {
            $oldorder = $Paylog->where(array('orderid' => $param['out_trade_no']))->find();
        }

        $kt = substr($param['auth_code'], 0, 2);
        if ($kt >= 25 && $kt <= 30) {
            if ($machinfos['ali_merid'] !== '') {
                $pays['pay_fs'] = 3;
                $pays['source_type'] = isset($param['source_type'])?$param['source_type']:"web";
                if (isset($oldorder) && $oldorder['pay_statu'] == 0) {
                    $param['orderid'] = $param['out_trade_no'];
                    $Paylog->save($pays, ['orderid' => $param['out_trade_no']]);
                } else {
                    $pays['orderid'] = $param['orderid'];
                    $Paylog->save($pays);
                }

                return $this->alipay($param);
            } else {
                $rarr['return_code'] = "SUCCESS";
                $rarr['return_msg'] = '';
                $rarr['result_code'] = 'FAIL';
                $rarr['result_msg'] = '该商户未开通支付宝支付通道';
            }
        } elseif ($kt >= 10 && $kt <= 15) {
            if ($machinfos['sub_mch_id'] !== '') {
                $pays['pay_fs'] = 2;
                $pays['source_type'] = isset($param['source_type'])?$param['source_type']:"web";
                if (isset($oldorder) && $oldorder['pay_statu'] == 0) {
                    $param['orderid'] = $param['out_trade_no'];
                    $Paylog->save($pays, ['orderid' => $param['out_trade_no']]);
                } else {
                    $pays['orderid'] = $param['orderid'];
                    $Paylog->save($pays);
                }
                return $this->wxpay($param);
            } else {
                $rarr['return_code'] = "SUCCESS";
                $rarr['return_msg'] = '';
                $rarr['result_code'] = 'FAIL';
                $rarr['result_msg'] = '该商户未开通微信支付通道';
            }

        } else {
            $rarr['return_code'] = "SUCCESS";
            $rarr['return_msg'] = '';
            $rarr['result_code'] = 'FAIL';
            $rarr['result_msg'] = '条码格式错误';
        }
        return $rarr;

    }

    public function getcheckpay($param, $pay_fs)
    {
        if ($pay_fs || $pay_fs == "0") {
            switch ($pay_fs) {
                case '0':
                    $rarr = $this->wxcheckpay($param);
                    break;
                case '1':
                    $rarr = $this->alicheckpay($param);
                    break;
                case '2':
                    $rarr = $this->wxcheckpay($param);
                    break;
                case '3':
                    $rarr = $this->alicheckpay($param);
                    break;
                case '8':
                    $rarr = $this->wxcheckpay($param);
                    break;
            }

        } else {
            $rarr['return_code'] = "SUCCESS";
            $rarr['result_code'] = 'FAIL';
            $rarr['return_msg'] = '订单编号不存在';
            $rarr['result_msg'] = "订单编号不存在";
        }
        return $rarr;
    }

    //微信会员卡支付
    public function wx_card_pay($param)
    {
        //会员卡支付

        if ($param['confirm'] == "no") {
            //判断是否为0
            $cardinfos = $this->getcard($param);
            if ($cardinfos !== "error") {
                if ($param['total_fee'] <> 0) {

                    $arr['num'] = $param['total_fee'];
                    $arr['merchantid'] = $param['merchantid'];
                    $arr['device_id'] = $param['device_id'];
                    $arr['card_code'] = $cardinfos['code'];
                    $arr['orderid'] = $param['orderid'];
                    $Cards = new Cards();

                    $arrs = $Cards->cardbalancecon($arr);
                    if ($arrs['result_code'] == "SUCCESS") {
                        $arrc = $this->wxpay_statu("", $param['merchantid'], $arrs['out_trade_no']);
                    } else {
                        $arrc = $arrs;
                    }
                } else {
                    $arrc['return_code'] = "SUCCESS";
                    $arrc['result_code'] = "FAIL";
                    $arrc['return_msg'] = "";
                    $arrc['result_msg'] = "请输入正确的支付金额";

                }
            } else {
                $arrc['return_code'] = "SUCCESS";
                $arrc['result_code'] = "FAIL";
                $arrc['return_msg'] = "";
                $arrc['result_msg'] = "未获取到用户领卡信息或授权码已过期";
            }

        } else {
            $arrc['return_code'] = "SUCCESS";
            $arrc['return_msg'] = '';
            $arrc['result_code'] = 'NOCARD';
            $arrc['result_msg'] = '未查询到会员信息或该笔订单使用电子支付';
        }
        return $arrc;

    }

    //微信支付
    public function wxpay($param)
    {
//        $ActionLogs = new ActionLogs();
//        $ActionLogs->writelog("osapi", "clientlog", "wxpay", "client:", $param);
        try {
            //判断是否为押金支付
            if (isset($param['pay_cate']) && $param['pay_cate'] == "wx_deposit") {
                $pays['pay_fs'] = 20;
                $Paylog = new Paylog();

                $Paylog->save($pays, ['orderid' => $param['orderid']]);
                $DepositPay = new DepositPay();
                $rarr = $DepositPay->wxpay($param);
            } else {
                $s = $this->wx_card_pay($param);
                if ($s['result_code'] == "NOCARD") {

                    $map['id'] = $param['merchantid'];
                    $Merchant = new Merchant();
                    $Agent = new Agent();
                    $WxOpen = new WxOpen();
                    $config = $Merchant->where($map)->find();
                    $agent = $Agent->where(array('id' => $config['agent']))->find();
                    $users = $WxOpen->where(array('id' => $agent['wx_open_id']))->find();
                    $userwx = $WxOpen->where(array('id' => $config['wx_open_id']))->find();
                    $options = array(
                        'appid' => $users['authorizer_appid'], // 填写高级调用功能的app id
                        'partnerid' => $agent['partnerid'], // 财付通商户身份标识
                        'partnerkey' => $agent['partnerkey'], // 财付通商户权限密钥Key
                    );
                    $sh = $param['merchantid'];
                    $weObj = new Wxobjopen($options);
                    //充值

                    if ($param['pay_cate'] == "recharge") {
                        $zk_price = 0;
                    } else {
                        $MachExtend = new MachExtend();
                        $machzk = $MachExtend->get_machzk($param);
                        //已有门店折扣的情况下不再查询会员折扣
                        if ($machzk['is_machzk'] == 'Y'){
                            $zk_price = $machzk['zk_price'];
                        }else {
                            $zk_price = $this->getzk($param);
                        }
//                        $zk_price = $this->getzk($param);
                    }
                    $pay_fees = $param['total_fee'] - $zk_price;

                    //END
                    //支付金额保留两位小数
                    $price = $this->format_price($pay_fees);
                    //END
                    $appid = $users['authorizer_appid'];
                    $mch_id = $agent['partnerid'];
                    $out_trade_no = $param['orderid'];
                    $body = "快捷支付";
                    $sub_mch_id = $config['sub_mch_id'];
                    if ($userwx['authorizer_appid'] !== $appid) {
                        $sub_appid = $userwx['authorizer_appid'];
                    } else {
                        $sub_appid = '';
                    }
                    $total_fee = $price * 100;
                    if(filter_var($param['client_ip'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
                        $spbill_create_ip = $param['client_ip'];
                    }
                    else{
                        $spbill_create_ip = "123.206.180.145";
                    }
                    $nonce_str = $weObj->generateNonceStr();
                    $auth_code = $param['auth_code'];
                    $arrdata = array(
                        "appid" => $appid,
                        'sub_appid' => $sub_appid,
                        "mch_id" => $mch_id,
                        "sub_mch_id" => $sub_mch_id,
                        "nonce_str" => $nonce_str,
                        "body" => $body,
                        "out_trade_no" => $out_trade_no,
                        "total_fee" => $total_fee,
                        "spbill_create_ip" => $spbill_create_ip,
                        "auth_code" => $auth_code,
                        "receipt" => $config['efp_receipt'],
                        "profit_sharing" => $config['is_profit'],
                    );
                    $pay_xml = $weObj->createWxPackageXml($arrdata);
//                $pay_xml = $weObj->createmicroPackageXml($appid, $sub_appid, $mch_id, $out_trade_no, $body, $sub_mch_id, $total_fee, $spbill_create_ip, $nonce_str, $auth_code);
                    $pay_xml = $weObj->Mircopay_post($pay_xml);

                    $rarr = $this->wxpay_statu($pay_xml, $sh, $out_trade_no);

                } else {
                    $rarr = $s;
                }
            }
        } catch (\Exception $e) {
            $rarr['return_code'] = "FAIL";
            $rarr['return_msg'] = '系统错误';
            $rarr['result_code'] = 'FAIL';
            $rarr['result_msg'] = '系统错误' . $e->getMessage();
        }
        return $rarr;


    }

    public function wxpay_statu($pay_xml, $id, $orderid)
    {
        try {
            $Paylog = new Paylog();
//            return $pay_xml;
            $payinfoa = $Paylog->where(['orderid' => $orderid])->find();


            if ($payinfoa['pay_fs'] == 0 || $payinfoa['pay_fs'] == 2) {

                if ($pay_xml['return_code'] == "SUCCESS") {
                    if ($pay_xml['result_code'] == "FAIL") {

                        $arrc['return_code'] = "SUCCESS";
                        if ($pay_xml['err_code'] == "USERPAYING") {
                            $arrc['result_code'] = $pay_xml['err_code'];
                        } else {
                            $arrc['result_code'] = "FAIL";
                        }
                        $arrc['return_msg'] = translate($pay_xml['err_code']);
                        $arrc['result_msg'] = translate($pay_xml['err_code_des']);
                        $arrc['out_trade_no'] = $payinfoa['orderid'];
                        $arrc['trade_no'] = $payinfoa['trade_no'];


                    } else {
                        if ($pay_xml['return_code'] && $pay_xml['result_code'] != "SUCCESS") {
                            $arrc['return_code'] = "SUCCESS";
                            $arrc['result_code'] = "FAIL";
                            $arrc['return_msg'] = translate($pay_xml['err_code']);
                            $arrc['result_msg'] = translate($pay_xml['err_code_des']);
                        } elseif (isset($pay_xml['trade_state']) && $pay_xml['trade_state'] != "SUCCESS") {
                            $arrc['return_code'] = "SUCCESS";
                            if ($pay_xml['trade_state'] == "USERPAYING") {
                                $arrc = $this->getorderinfo($orderid);
                                $arrc['result_code'] = "USERPAYING";
                                $arrc['out_trade_no'] = $payinfoa['orderid'];
                                $arrc['trade_no'] = $payinfoa['trade_no'];
                            } else {
                                $arrc['result_code'] = "FAIL";
                            }
                            $arrc['result_code'] = $pay_xml['trade_state'];
                            $arrc['return_msg'] = translate($pay_xml['trade_state']);
                            $arrc['result_msg'] = translate($pay_xml['trade_state']);
                        } else {
                            $pays['orderno'] = $pay_xml['transaction_id'];
                            $pays['pay_time'] = date('Y-m-d H:i:s', strtotime($pay_xml['time_end']));
                            $pays['pay_statu'] = 1;
                            $pays['openid'] = $pay_xml['openid'];
                            $pays['sub_openid'] = isset($pay_xml['sub_openid']) ? $pay_xml['sub_openid'] : "";
                            $pays['payinfo'] = json_encode($pay_xml);
                            $pays['price'] = $pay_xml['total_fee'] / 100;
                            $Pub = new Pub();
                            $pays['service_charge'] = $Pub->service_charge($payinfoa['mid'], $pays['price'], $payinfoa['pay_fs']);

                            //卡券核销

                            $gel_card_zk = $payinfoa['gel_card_zk'];
                            if (isset($gel_card_zk) && $gel_card_zk > 0) {
                                $hx_card = $Paylog->where(['orderid' => $orderid])->value('hx_card');
                                $hx_data['merchid'] = $Paylog->where(['orderid' => $orderid])->value('mid');
                                $hx_data['cashier'] = $Paylog->where(['orderid' => $orderid])->value('cashier');
                                $hx_data['orderid'] = $orderid;
                                $CardDedu = new CardDedu();
                                $CardDedu->pay_hx_card($hx_data);

                            }
                            //end
                            $Paylog->save($pays, ['orderid' => $orderid]);
                            if (isset($pay_xml['sub_openid'])) {
                                $barr['openid'] = $pay_xml['sub_openid'];
                            } else {
                                $barr['openid'] = $pay_xml['openid'];
                            }

                            $barr['price'] = $pay_xml['total_fee'] / 100;
                            $Bonus = new Bonus();
                            $arr['price'] = $pays['price'];
                            $payinfob = $Paylog->where(['orderid' => $orderid])->find();
                            $arr['merchantid'] = $payinfob['mid'];
                            $arr['username'] = !empty($payinfob['cashier']) ? $payinfob['cashier'] : $payinfob['d_cashier'];

                            if ($payinfoa['pay_cate'] !== "recharge") {
                                if ($payinfoa['tzzt'] == 0 || $payinfoa['tzzt'] == '0') {
                                    $arr['orderid'] = $orderid;
                                    $Bonus->pay_bonus($barr['openid'], $arr);
//                                    $Deviceobj = new Deviceobj();
//                                    $s=$Deviceobj->ylb_sendvoice($orderid);

                                }
                            }
                            if ($payinfoa['tzzt'] == 0) {
                                $Fenzhang = new Fenzhang();
                                $Fenzhang->createlog($payinfob);


                            }
                            $TemplateMsg = new TemplateMsg();
                            $TemplateMsg->send_tpl('pay', array('merchantid' => $id, 'orderid' => $orderid));

                            $FeiePrint = new FeiePrint();
                            $FeiePrint->sendprint($orderid);
//                        action('index/wxauth/sendtemplate', array($id, $orderid));
                            //返回结果
                            $arrc = $this->getorderinfo($orderid);
                            $Notify=new CreateNotify();
                            $param['out_trade_no']=$orderid;
                            $param['merchantid']=$id;
                            $Notify->pay_notify($param);

                        }

                    }
                } elseif ($pay_xml['return_code'] == "FAIL") {
                    $arrc['return_code'] = "SUCCESS";
                    $arrc['result_code'] = "FAIL";
                    $arrc['return_msg'] = translate($pay_xml['return_msg']);
                    $arrc['result_msg'] = translate($pay_xml['return_msg']);
                }
            } elseif ($payinfoa['pay_fs'] == 8) {

                if ($payinfoa['pay_statu'] == 1) {
                    $TemplateMsg = new TemplateMsg();
                    $TemplateMsg->send_tpl('pay', array('merchantid' => $id, 'orderid' => $orderid));
                    $FeiePrint = new FeiePrint();
                    $FeiePrint->sendprint($orderid);
//                    $Deviceobj = new Deviceobj();
//                    $s=$Deviceobj->ylb_sendvoice($orderid);

                    $arrc = $this->getorderinfo($orderid);
                    $Notify=new CreateNotify();
                    $param['out_trade_no']=$orderid;
                    $param['merchantid']=$id;
                    $Notify->pay_notify($param);
                } else {
                    $arrc['return_code'] = "SUCCESS";
                    $arrc['result_code'] = "FAIL";
                    $arrc['return_msg'] = "支付失败";
                    $arrc['result_msg'] = "支付失败";
                }
            }


        } catch (\Exception $e) {
            $arrc['return_code'] = "FAIL";
            $arrc['return_msg'] = '系统错误';
            $arrc['result_code'] = 'FAIL';
            $arrc['result_msg'] = '系统错误' . $e->getMessage();



        }
        $ActionLogs = new ActionLogs();
        $ActionLogs->writelog("osapi", "clientlog", "wxpay_statu", "res:", $arrc);
        return $arrc;


    }

    private function getzk($param)
    {

        $openid = $this->getsubopenid($param);
        $CardDedu = new CardDedu();
        $CardMember = new CardMember();
        $arr['add_balance'] = $param['total_fee'];
        $user = $this->get_card_userinfo($param['merchantid'], $openid);
        if ($user) {
            $cardus = $CardMember->where(array('card_id' => $user['card_id']))->find();
            if ($cardus['is_zf_discount'] == 1 || $cardus['is_dj_discount'] == 1 || $cardus['is_dedu_cards'] == 1) {
                $arrc = $CardDedu->paygetzk($arr, $user, $cardus);
            } else {
                $arrc['dis_card_zk'] = 0;                                                 //会员折扣
                $arrc['vip_card_zk'] = 0;                                                 //等级折扣
                $arrc['gel_card_zk'] = 0;                                                 //卡券折扣
                $arrc['hx_card'] = "0000";                                                //要核销的卡券
                $arrc['yf_balance'] = $arr['add_balance'];                                //应付金额
            }
        } else {
//            $datas['add_balance'] = 0;
//            $datas['del_balance'] = 0;                                               //实际支付额
            $arrc['dis_card_zk'] = 0;                                                 //会员折扣
            $arrc['vip_card_zk'] = 0;                                                 //等级折扣
            $arrc['gel_card_zk'] = 0;                                                 //卡券折扣
            $arrc['hx_card'] = "0000";                                                //要核销的卡券
            $arrc['yf_balance'] = $arr['add_balance'];                                //应付金额


        }
        $zk_price = $arrc['dis_card_zk'] + $arrc['vip_card_zk'] + $arrc['gel_card_zk'];
        $datas['dis_card_zk'] = $arrc['dis_card_zk'];                                                 //会员折扣
        $datas['vip_card_zk'] = $arrc['vip_card_zk'];                                                     //等级折扣
        $datas['gel_card_zk'] = $arrc['gel_card_zk'];
        $datas['yf_price'] = $arr['add_balance'];
        $datas['hx_card'] = $arrc['hx_card'];
        $datas['zk_price'] = $zk_price;
        $datas['card_num'] = $user['code'];
        $Paylog = new Paylog();
        $Paylog->save($datas, array('orderid' => $param['orderid']));

        return $zk_price;

    }

    public function wxcheckpay($param)
    {
        try {
            $orderid = $param['out_trade_no'];

            $id = $param['merchantid'];
            $payxml = $this->wxorderquery($id, $orderid);
            $rarr = $this->wxpay_statu($payxml, $id, $orderid);

        } catch (\Exception $e) {
            $rarr['return_code'] = "FAIL";
            $rarr['return_msg'] = '系统错误';
            $rarr['result_code'] = 'FAIL';
            $rarr['result_msg'] = '系统错误' . $e->getMessage();
        }

        return $rarr;


    }

    public function wxorderquery($id, $orderid)
    {

        try {
            $map['id'] = $id;
            $config = Db::name('Merchant')->where($map)->find();
            $agent = Db::name('agent')->where(array('id' => $config['agent']))->find();
            $users = Db::name('wx_open')->where(array('id' => $agent['wx_open_id']))->find();
            $userwx = Db::name('wx_open')->where(array('id' => $config['wx_open_id']))->find();

            $options = array(
                'appid' => $users['authorizer_appid'], // 填写高级调用功能的app id
                'partnerid' => $agent['partnerid'], // 财付通商户身份标识
                'partnerkey' => $agent['partnerkey'], // 财付通商户权限密钥Key
            );
            trace( "wxorderquery-1：" . json_encode($options,256),'SysRunErrorLog');
            $weObj = new Wxobjopen($options);
            $appid = $users['authorizer_appid'];
            $mch_id = $agent['partnerid'];
            $out_trade_no = $orderid;
            $sub_mch_id = $config['sub_mch_id'];
            $sub_appid = $userwx['authorizer_appid'];
            $nonce_str = $weObj->generateNonceStr();
            $arrdata = array(
                "appid" => $appid,
                "mch_id" => $mch_id,
                "sub_appid" => $sub_appid,
                "sub_mch_id" => $sub_mch_id,
                "nonce_str" => $nonce_str,
                "out_trade_no" => $out_trade_no
            );
            trace( "wxorderquery-2：" . json_encode($arrdata,256),'SysRunErrorLog');
            $orderxml = $weObj->createWxPackageXml($arrdata);
            trace( "wxorderquery-3：" . json_encode($orderxml,256),'SysRunErrorLog');
//            $orderxml = $weObj->createOrderXml($appid, $mch_id, $sub_appid, $sub_mch_id, $out_trade_no, $nonce_str);

            $rarr = $weObj->getPayNum($orderxml);
            trace( "wxorderquery-4：" . json_encode($rarr,256),'SysRunErrorLog');
        } catch (\Exception $e) {
            $rarr['return_code'] = "FAIL";
            $rarr['return_msg'] = '系统错误';
            $rarr['result_code'] = 'FAIL';
            $rarr['result_msg'] = '系统错误' . $e->getMessage();;
        }
        return $rarr;

    }

    //支付宝
    public function alipay($param)
    {
//        try {
        if (isset($param['pay_cate']) && $param['pay_cate'] == "wx_deposit") {
            $pays['pay_fs'] = 30;
            $Paylog = new Paylog();

            $Paylog->save($pays, ['orderid' => $param['orderid']]);
            $DepositPay = new DepositPay();
            $rarr = $DepositPay->alipay($param);
        } else {
            $User = new Merchant();
            $Agent = new Agent();
            $users = $User->where(array('id' => $param['merchantid']))->find();
            $agent = $Agent->where(array('id' => $users['agent']))->find();
            $options = array(
                'appid' => $agent['ali_app_id'], // 填写高级调用功能的app id
                'rsaPrivateKey' => $agent['ali_app_key'],
            );
            $aliObj = new Alipayobj($options);
            //充值时不再获取折扣
            if ($param['pay_cate'] == "recharge") {
                $pay_fees = $param['total_fee'];
            } else {
                //获取门店折扣
                $MachExtend = new MachExtend();
                $res_machzk = $MachExtend->get_machzk($param);
                //是否有折扣
                if ($res_machzk['is_machzk'] == 'Y') {
                    $zk_price = $res_machzk['zk_price'];
                    $pay_fees = $param['total_fee'] - $zk_price;//END

                } else {
                    $pay_fees = $param['total_fee'];
                }
                //END
            }
            //支付金额保留两位小数
            $price = $this->format_price($pay_fees);
            //END
            $sh = $param['merchantid'];
            $out_trade_no = $param['orderid'];
            $body = "快捷支付";
            $auth_code = $param['auth_code'];
            $total_fee = $price;
            $data['app_id'] = $agent['ali_app_id'];
            $data['method'] = "alipay.trade.pay";
            $data['charset'] = "UTF-8";
            $data['sign_type'] = "RSA2";
            $data['timestamp'] = date('Y-m-d H:i:s');
            $data['version'] = "1.0";
            $data['notify_url'] = 'http://api.wunengkeji.com';
            $data['app_auth_token'] = $users['ali_merid'];
            $data['biz_content'] = json_encode(array(
                'out_trade_no' => $out_trade_no,
                'scene' => 'bar_code',
                'auth_code' => $auth_code,
                'total_amount' => $total_fee,
                'subject' => $body,
                'alipay_store_id' => $users['ali_store_id'],
//                'store_id'=>I('get.id'),
                'extend_params' => array(
                    'sys_service_provider_id' => $agent['sys_service_provider_id'],
                ),
            ));
            $signContent = $aliObj->rsaSign($data, $signType = "RSA2");
            $data['sign'] = $signContent;
            $sj = $aliObj->scanpay($data);
            $content = json_decode(iconv("GB2312", "UTF-8//IGNORE", $sj), true);
            $rarr = $this->alipay_statu($content['alipay_trade_pay_response'], $sh, $out_trade_no);
        }
        return $rarr;

    }

    public function alipay_statu($contents, $sh, $orderid, $fs = '')
    {

//        try {
//            return $contents;
        $Paylog = new Paylog();
        $payinfo = $Paylog->where(['orderid' => $orderid])->find();
        if ($payinfo['pay_fs'] == 1 || $payinfo['pay_fs'] == 3) {
            if ($fs == "checkpay") {


                if ($contents['code'] == 10000) {
                    switch ($contents['trade_status']) {
                        case 'WAIT_BUYER_PAY':
                            $arrc = $this->getorderinfo($orderid);
                            $arrc['return_code'] = "SUCCESS";
                            $arrc['result_code'] = "USERPAYING";
                            $arrc['return_msg'] = translate($contents['trade_status']);
                            $arrc['result_msg'] = translate($contents['trade_status']);
                            $arrc['out_trade_no'] = $payinfo['orderid'];
                            $arrc['trade_no'] = $payinfo['trade_no'];
                            break;
                        case 'TRADE_CLOSED':
                            $arrc['return_code'] = "SUCCESS";
                            $arrc['result_code'] = "FAIL";
                            $arrc['return_msg'] = translate($contents['trade_status']);
                            $arrc['result_msg'] = translate($contents['trade_status']);
                            break;
                        case 'TRADE_FINISHED':
                            $arrc['return_code'] = "SUCCESS";
                            $arrc['result_code'] = "FAIL";
                            $arrc['return_msg'] = translate($contents['trade_status']);
                            $arrc['result_msg'] = translate($contents['trade_status']);
                            break;
                        case 'TRADE_SUCCESS':
                            $pays['pay_statu'] = 1;
                            $pays['orderno'] = $contents['trade_no'];
                            $pays['openid'] = $contents['buyer_user_id'];
                            $pays['pay_time'] = $contents['send_pay_date'];
                            $pays['price'] = $contents['total_amount'];
                            $pays['payinfo'] = json_encode($contents, JSON_UNESCAPED_UNICODE);
                            $Pub = new Pub();
                            $pays['service_charge'] = $Pub->service_charge($payinfo['mid'], $pays['price'], $payinfo['pay_fs']);
                            $Paylog = new Paylog();
                            $Paylog->save($pays, ['orderid' => $orderid]);
                            $TemplateMsg = new TemplateMsg();
                            $TemplateMsg->send_tpl('pay', array('merchantid' => $payinfo['mid'], 'orderid' => $orderid));
                            $FeiePrint = new FeiePrint();
                            $FeiePrint->sendprint($orderid);
                            $arrc = $this->getorderinfo($orderid);
                            break;
                    }

                } else {
                    $arrc['return_code'] = "SUCCESS";
                    $arrc['result_code'] = "FAIL";
                    $arrc['return_msg'] = translate($contents['code']);
                    $arrc['result_msg'] = translate($contents['code']);
                }

            } else {
                if ($contents['code'] == 10000) {

                    if ($contents['msg'] = "Success") {

                        $pays['pay_statu'] = 1;
                        $pays['orderno'] = $contents['trade_no'];
                        $pays['pay_time'] = $contents['gmt_payment'];
                        $pays['price'] = $contents['total_amount'];
                        $pays['openid'] = $contents['buyer_user_id'];
                        $pays['payinfo'] = json_encode($contents, JSON_UNESCAPED_UNICODE);
                        $Pub = new Pub();
                        $pays['service_charge'] = $Pub->service_charge($payinfo['mid'], $pays['price'], $payinfo['pay_fs']);
                        $Paylog = new Paylog();
                        $Paylog->save($pays, ['orderid' => $orderid]);
                        $TemplateMsg = new TemplateMsg();
                        $TemplateMsg->send_tpl('pay', array('merchantid' => $payinfo['mid'], 'orderid' => $orderid));
                        $FeiePrint = new FeiePrint();
                        $FeiePrint->sendprint($orderid);
                        $arrc = $this->getorderinfo($orderid);

                    }
                } elseif ($contents['code'] == 10003) {
                    $arrc = $this->getorderinfo($orderid);
                    $arrc['return_code'] = "SUCCESS";
                    $arrc['result_code'] = "USERPAYING";
                    $arrc['return_msg'] = "等待用户输入密码";
                    $arrc['result_msg'] = "等待用户输入密码";
                    $arrc['out_trade_no'] = $payinfo['orderid'];
                    $arrc['trade_no'] = $payinfo['trade_no'];


                } elseif ($contents['code'] = 40004) {
                    $arrc['return_code'] = "SUCCESS";
                    $arrc['result_code'] = "FAIL";
                    $arrc['return_msg'] = translate($contents['sub_msg']);
                    $arrc['result_msg'] = translate($contents['sub_msg']);

                }
            }
        }
//        } catch (\Exception $e) {
//            $arrc['return_code'] = "FAIL";
//            $arrc['return_msg'] = '系统错误';
//            $arrc['result_code'] = 'FAIL';
//            $arrc['result_msg'] = '系统错误' . $e->getMessage();
//        }
        return $arrc;
    }

    public function alicheckpay($param)
    {

        try {
            $orderid = $param['out_trade_no'];
            $id = $param['merchantid'];
            $payxml = $this->aliorderquery($id, $orderid);
            $rarr = $this->alipay_statu($payxml['alipay_trade_query_response'], $id, $orderid, "checkpay");

        } catch (\Exception $e) {
            $rarr['return_code'] = "FAIL";
            $rarr['return_msg'] = '系统错误';
            $rarr['result_code'] = 'FAIL';
            $rarr['result_msg'] = '系统错误' . $e->getMessage();
        }
        return $rarr;


    }

    public function aliorderquery($id, $orderid)
    {

        $User = new Merchant();
        $Agent = new Agent();
        $users = $User->where(array('id' => $id))->find();
        $agent = $Agent->where(array('id' => $users['agent']))->find();

        $options = array(

            'appid' => $agent['ali_app_id'], // 填写高级调用功能的app id
            'rsaPrivateKey' => $agent['ali_app_key'],

        );
        $out_trade_no = $orderid;
        $aliObj = new Alipayobj($options);
        $data['app_id'] = $agent['ali_app_id'];
        $data['method'] = "alipay.trade.query";
        $data['charset'] = "UTF-8";
        $data['sign_type'] = "RSA2";
        $data['timestamp'] = date('Y-m-d H:i:s');
        $data['version'] = "1.0";
        $data['notify_url'] = 'https://tp5.weilinzhou.com';
        $data['app_auth_token'] = $users['ali_merid'];
        $data['biz_content'] = json_encode(array(
            'out_trade_no' => $out_trade_no,
        ));
        $signContent = $aliObj->rsaSign($data, $signType = "RSA2");
        $data['sign'] = $signContent;
        $sj = $aliObj->scanpay($data);
        return $content = json_decode(iconv("GB2312", "UTF-8//IGNORE", $sj), true);


    }

}